﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
using BLL.Utils;
using DAL.Entity;
using DAL.Persistencia;

namespace NewTierra.Pages.Operacoes
{
    public partial class SubServicosCarrinhoNew : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //VerSubServicosAdicionados();
                VerSubServicos();
                BuscaTransfer();
            }
        }

        #region Popula Dados

        protected void PopulaGridMServicos()
        {
            try
            {
                MontaServicoDAL ms = new MontaServicoDAL();
                SupplierDAL sd = new SupplierDAL();

                Supplier s = sd.ObterSupplierPorNome(txtSupplier.Text);

                DateTime From = Convert.ToDateTime(Request.QueryString["DataFrom"]);
                DateTime To = Convert.ToDateTime(Request.QueryString["DataTo"]);

                GridMServicos.DataSource = ms.ListarTodosCondicaoMServicoSub(s.S_id, From, To);
                GridMServicos.DataBind();

            }
            catch (Exception ex)
            {
                lblMsgErro.Text = ex.Message;
            }
        }

        protected void VerSubServicosAdicionados()
        {
            try
            {

                ServicoCompletoFileDAL msd = new ServicoCompletoFileDAL();

                GridSubServPorTemporada.DataSource = msd.ListarTodosSubServicoPorTransfer(Convert.ToInt32(Request.QueryString["IdTrans"]), 1);
                GridSubServPorTemporada.DataBind();

            }
            catch (Exception ex)
            {

                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgErro.Text = ex.Message;
            }
        }

        protected void VerSubServicos()
        {
            try
            {
                SubServicosFileDAL ssfd = new SubServicosFileDAL();

                if (Request.QueryString["Type"].Equals("Q"))
                    GridSubServPorTemporada.DataSource = ssfd.ListarTodosRange(Convert.ToInt32(Request.QueryString["IdTrans"]), 0);
                else
                    GridSubServPorTemporada.DataSource = ssfd.ListarTodosRange(0, Convert.ToInt32(Request.QueryString["IdTrans"]));

                GridSubServPorTemporada.DataBind();

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgErro.Text = ex.Message;
            }
        }

        #endregion

        #region Regras SubServicos

        protected void imgAtualizaTarifaSubServico_Command(object sender, CommandEventArgs e)
        {
            try
            {
                int myid = Convert.ToInt32(e.CommandArgument);

                ServicoCompletoFileDAL scd = new ServicoCompletoFileDAL();

                FileTransfersDAL ftd = new FileTransfersDAL();

                File_Transfers ft = ftd.ObterPorId(Convert.ToInt32(Request.QueryString["IdTrans"]));

                foreach (GridViewRow item in GridSubServPorTemporada.Rows)
                {

                    TextBox txtValorSubServico = (TextBox)item.FindControl("txtValorSubServico");

                    Servico_Completo_File sc = new Servico_Completo_File();

                    if (Convert.ToInt32(item.Cells[0].Text) == myid)
                    {
                        sc.Valor = Convert.ToDecimal(txtValorSubServico.Text);
                        sc.ServicoCompletoFile_id = myid;

                        scd.AtualizarValor(sc);
                    }
                }

                AtualizaValoresSubServico(Convert.ToInt32(Request.QueryString["IdTrans"]));
                VerSubServicosAdicionados();
                BuscaTransfer();

            }
            catch (Exception ex)
            {
                lblMsgErro.Text = ex.Message;
            }
        }

        protected void imgAtualizaTarifaSubs(object sender, CommandEventArgs e)
        {
            try
            {

                SubServicosFileDAL ssfd = new SubServicosFileDAL();

                string[] pars = e.CommandArgument.ToString().Split(',');

                foreach (GridViewRow item in GridSubServPorTemporada.Rows)
                {

                    TextBox txtValorSubServico = (TextBox)item.FindControl("txtValorSubServico");

                    if (item.DataItemIndex == Convert.ToInt32(pars[0]))
                    {
                        SubServicosFile sf = ssfd.ObterPorId(Convert.ToInt32(pars[1]));
                        sf.Valor = Convert.ToDecimal(txtValorSubServico.Text);
                        ssfd.Atualiza(sf);
                    }
                }

                VerSubServicos();
                BuscaTransfer();

                if (Request.QueryString["Type"].Equals("Q"))
                {
                    AcertaValoresGridRange(Convert.ToInt32(Request.QueryString["IdTrans"]));
                }
                else
                {
                    AcertaValoresGridQTrf(Convert.ToInt32(Request.QueryString["IdTrans"]));
                }

                MostrarMsg("Valor atualizado com sucesso.");
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void ExluirSubServico(object sender, CommandEventArgs e)
        {
            try
            {
                int myid = Convert.ToInt32(e.CommandArgument);

                ServicoCompletoFileDAL scfd = new ServicoCompletoFileDAL();

                Servico_Completo_File scf = scfd.ObterPorId(myid);

                int IdTransf = Convert.ToInt32(scf.File_Transf_id);

                scfd.Excluir(scf);

                AtualizaValoresSubServico(IdTransf);
                VerSubServicosAdicionados();
                BuscaTransfer();
            }
            catch (Exception ex)
            {
                lblMsgErro.Text = ex.Message;
            }
        }

        protected void AtualizaValoresSubServico(int IdTransf)
        {
            try
            {

                ServicoCompletoFileDAL scfd = new ServicoCompletoFileDAL();

                double somaTotal = 0;

                foreach (Servico_Completo_File item in scfd.ListarTodosPorTransf(IdTransf))
                {
                    somaTotal = somaTotal + Convert.ToDouble(item.Valor);
                }

                FileTransfersDAL ftd = new FileTransfersDAL();
                File_Transfers ft = new File_Transfers();

                ft.Transf_valor = Convert.ToDecimal(somaTotal);
                ft.Transf_venda = Convert.ToDecimal(somaTotal);
                ft.Transf_total = Convert.ToDecimal(somaTotal);
                ft.File_Transf_id = IdTransf;

                ftd.AtualizarValorTotal(ft);
            }
            catch (Exception ex)
            {
                lblMsgErro.Text = ex.Message;
            }
        }

        protected void EditarMServico(object sender, CommandEventArgs e)
        {
            try
            {
                int myid = Convert.ToInt32(e.CommandArgument);

                ServicoCompletoFileDAL scd = new ServicoCompletoFileDAL();
                MontaServicoValoresDAL msd = new MontaServicoValoresDAL();

                Servico_Completo_File sc = new Servico_Completo_File();

                //if (scd.VerificaMServicoTemp(myid, Convert.ToInt32(Request.QueryString["idMS"])))
                //{
                //    MostrarMsg("Este Subserviço já foi adicionado a este serviço.");
                //    return;
                //}

                FileTransfersDAL ftd = new FileTransfersDAL();
                CambioDAL cambDal = new CambioDAL();

                File_Transfers ft = ftd.ObterPorId(Convert.ToInt32(Request.QueryString["IdTrans"]));

                if (scd.VerirficaExisteBase(myid, Convert.ToInt32(Request.QueryString["PayPax"]), Convert.ToInt32(Request.QueryString["BaseIndex"])))
                {

                    Monta_Servico_Valores msv = scd.ObterValor(myid, Convert.ToInt32(Request.QueryString["PayPax"]), Convert.ToInt32(Request.QueryString["BaseIndex"]));

                    if (msv.S_Bases.Moeda_id != ft.Moeda_id)
                    {
                        Cambio camb = cambDal.ObterPorIdMoedaPara(msv.S_Bases.Moeda_id, Convert.ToInt32(ft.Moeda_id));

                        decimal valor = Convert.ToDecimal(scd.ObterValor(myid, Convert.ToInt32(Request.QueryString["PayPax"]), Convert.ToInt32(Request.QueryString["BaseIndex"])).MServico_Valores_Bulk_Total);

                        decimal valorComCambio = valor * Convert.ToDecimal(camb.Cambio1);

                        sc.Valor = valorComCambio;

                    }
                    else
                    {
                        sc.Valor = scd.ObterValor(myid, Convert.ToInt32(Request.QueryString["PayPax"]), Convert.ToInt32(Request.QueryString["BaseIndex"])).MServico_Valores_Bulk_Total;
                    }
                }
                else
                {
                    MostrarMsg("Não existe valor para base " + Request.QueryString["PayPax"]);
                    return;
                }

                sc.IdMServico = myid;
                sc.File_Transf_id = Convert.ToInt32(Request.QueryString["IdTrans"]);
                sc.Base_Index = Convert.ToInt32(Request.QueryString["BaseIndex"]);
                sc.Servicos_Id = Convert.ToInt32(Request.QueryString["IdServico"]);
                sc.ServicoCompleto_de = 0;
                sc.ServicoCompleto_ate = 0;

                scd.Salvar(sc);

                MostrarMsg("Subserviço adicionado com sucesso.");

                AtualizaValoresSubServico(Convert.ToInt32(Request.QueryString["IdTrans"]));
                VerSubServicosAdicionados();
                BuscaTransfer();
            }
            catch (Exception ex)
            {
                lblMsgErro.Text = ex.Message;
            }
        }

        protected void AddSubServ(object sender, CommandEventArgs e)
        {
            try
            {
                string[] pars = e.CommandArgument.ToString().Split(',');
                int myid = Convert.ToInt32(pars[0]);

                SubServicosFile sc = new SubServicosFile();
                
                SubServicosFileDAL ssfdal = new SubServicosFileDAL();
                ServicoCompletoFileDAL scd = new ServicoCompletoFileDAL();
                MontaServicoValoresDAL msd = new MontaServicoValoresDAL();
                FileTransfersDAL ftd = new FileTransfersDAL();
                QuoteTransDAL qtrdal = new QuoteTransDAL();
                CambioDAL cambDal = new CambioDAL();

                int idMoeda = 0;

                if (Request.QueryString["Type"].Equals("Q"))
                {
                    File_Transfers ft = ftd.ObterPorId(Convert.ToInt32(new RangeDal().ObterPorId(Convert.ToInt32(Request.QueryString["IdTrans"])).FileTabelaId));
                    idMoeda = (int)ft.Moeda_id;
                    sc.Ranges_id = Convert.ToInt32(Request.QueryString["IdTrans"]);
                }
                else
                {
                    Quote_Transf ft = qtrdal.ObterPorId(Convert.ToInt32(Request.QueryString["IdTrans"]));
                    idMoeda = (int)ft.Moeda_id;
                    sc.Quote_Transf_id = Convert.ToInt32(Request.QueryString["IdTrans"]);
                }

                string[] bas = Request.QueryString["PayPax"].ToString().Split('/');

                if (scd.VerirficaExisteBase(myid, Convert.ToInt32(bas[0]), Convert.ToInt32(Request.QueryString["BaseIndex"])))
                {
                    
                    Monta_Servico_Valores msv = scd.ObterValor(myid, Convert.ToInt32(bas[0]), Convert.ToInt32(Request.QueryString["BaseIndex"]));

                    if (msv.S_Bases.Moeda_id != idMoeda)
                    {
                        Cambio camb = cambDal.ObterPorIdMoedaPara(msv.S_Bases.Moeda_id, Convert.ToInt32(idMoeda));

                        decimal valor = Convert.ToDecimal(scd.ObterValor(myid, Convert.ToInt32(bas[0]), Convert.ToInt32(Request.QueryString["BaseIndex"])).MServico_Valores_Bulk_Total);

                        decimal valorComCambio = valor * Convert.ToDecimal(camb.Cambio1);

                        sc.Valor = valorComCambio;

                    }
                    else
                    {
                        sc.Valor = scd.ObterValor(myid, Convert.ToInt32(bas[0]), Convert.ToInt32(Request.QueryString["BaseIndex"])).MServico_Valores_Bulk_Total;
                    }
                }
                else
                {
                    MostrarMsg("Não existe valor para base " + Convert.ToInt32(bas[0]));
                    return;
                }

                foreach (GridViewRow item in GridMServicos.Rows)
                {
                    if (item.DataItemIndex == Convert.ToInt32(pars[1]))
                    {
                        sc.NomeFantasia = item.Cells[3].Text;
                        sc.NomeSubItem = item.Cells[4].Text;
                        break;
                    }
                }

                sc.NomeSupplier = txtSupplier.Text;
                sc.ServDe = bas[0];
                sc.ServAte = bas[1];

                ssfdal.Salvar(sc);               

                VerSubServicos();
                BuscaTransfer();

                if (Request.QueryString["Type"].Equals("Q"))
                {
                    AcertaValoresGridRange(Convert.ToInt32(Request.QueryString["IdTrans"]));
                }
                else
                {
                    AcertaValoresGridQTrf(Convert.ToInt32(Request.QueryString["IdTrans"]));
                }

                MostrarMsg("Subserviço adicionado com sucesso.");
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        #endregion

        #region Regras

        protected string Limit(object Desc, int length)
        {
            StringBuilder strDesc = new StringBuilder();
            strDesc.Insert(0, Desc.ToString());

            if (strDesc.Length > length)
            {
                return strDesc.ToString().Substring(0, length);
            }
            else
            { return strDesc.ToString(); }
        }

        protected void BuscaTransfer()
        {
            try
            {
                //FileTransfersDAL ftd = new FileTransfersDAL();
                //File_Transfers ft = ftd.ObterPorId(Convert.ToInt32(Request.QueryString["IdTrans"]));
                //txtValorTotal.Text = ft.Transf_valor.ToString();

                SubServicosFileDAL ssdf = new SubServicosFileDAL();

                if (Request.QueryString["Type"].Equals("Q"))
                    txtValorTotal.Text = ssdf.SomaTotal(Convert.ToInt32(Request.QueryString["IdTrans"]), 0).ToString();
                else
                    txtValorTotal.Text = ssdf.SomaTotal(0, Convert.ToInt32(Request.QueryString["IdTrans"])).ToString();

            }
            catch (Exception ex)
            {
                lblMsgErro.Text = ex.Message;
            }
        }

        [WebMethod]
        public static List<string> SearchSuppliers(string prefixText, int count)
        {
            try
            {
                SupplierDAL s = new SupplierDAL();

                List<Supplier> supp = s.ListarTodos(prefixText);

                List<string> lista = new List<string>();

                if (supp.Count == 0)
                {
                    lista.Add("Não existe supplier cadastrado com esse nome.");

                    return lista;
                }

                foreach (Supplier p in supp)
                {
                    lista.Add(p.S_nome);
                }

                return lista;
            }
            catch
            {
                throw;
            }
        }

        protected void btnFiltroNomeSupplier_Click(object sender, EventArgs e)
        {
            PopulaGridMServicos();
        }

        protected void AcertaValoresGridRange(int IdRange)
        {
            try
            {
                RangeDal rdal = new RangeDal();

                Ranges r = rdal.ObterPorId(IdRange);

                double venda = 0;
                double vall = Convert.ToDouble(txtValorTotal.Text);

                if (Convert.ToDecimal(r.markup) < 1)
                {
                    venda = (Convert.ToDouble(vall) / Convert.ToDouble(r.markup));
                }
                else
                {
                    venda = (Convert.ToDouble(vall) * Convert.ToDouble(r.markup) / 100) + Convert.ToDouble(vall);
                }

                ArredondaDAL arrd = new ArredondaDAL();

                string[] pars = Convert.ToDecimal(venda).ToString().Split(',');
                decimal valorArr = 0;

                if (pars.Count() > 1)
                {
                    Arredonda arr;

                    if (pars[1].Length == 1)
                    {
                        string val = pars[1] + 0;
                        arr = arrd.ObterArr(Convert.ToInt32(val.Substring(0, 2)));
                    }
                    else
                    {
                        arr = arrd.ObterArr(Convert.ToInt32(pars[1].Substring(0, 2)));
                    }

                    if (arr.Arredonda_recebe < 1)
                    {
                        valorArr = Convert.ToDecimal(pars[0]) + Convert.ToDecimal(arr.Arredonda_recebe);
                        venda = Convert.ToDouble(valorArr);
                    }
                    else
                    {
                        valorArr = Convert.ToDecimal(pars[0]) + Convert.ToDecimal(arr.Arredonda_recebe);
                        venda = Convert.ToDouble(valorArr);
                    }
                }

                double addDesconto = venda - (venda * Convert.ToDouble(r.desconto) / 100);                      

                r.VendaNet = Convert.ToDecimal(addDesconto);
                r.Venda = Convert.ToDecimal(addDesconto);
                r.ValorTotal = Convert.ToDecimal(addDesconto);
                r.Valor = Convert.ToDecimal(vall);

                rdal.AtualizarValores(r);

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void AcertaValoresGridQTrf(int IdQTransf)
        {
            try
            {
                QuoteTransDAL qtdal = new QuoteTransDAL();

                Quote_Transf qt = qtdal.ObterPorId(IdQTransf);                

                double venda = 0;
                double vall = Convert.ToDouble(txtValorTotal.Text);

                if (Convert.ToDecimal(qt.markup) < 1)
                {
                    venda = (Convert.ToDouble(vall) / Convert.ToDouble(qt.markup));
                }
                else
                {
                    venda = (Convert.ToDouble(vall) * Convert.ToDouble(qt.markup) / 100) + Convert.ToDouble(vall);
                }

                ArredondaDAL arrd = new ArredondaDAL();

                string[] pars = Convert.ToDecimal(venda).ToString().Split(',');
                decimal valorArr = 0;

                if (pars.Count() > 1)
                {
                    Arredonda arr;

                    if (pars[1].Length == 1)
                    {
                        string val = pars[1] + 0;
                        arr = arrd.ObterArr(Convert.ToInt32(val.Substring(0, 2)));
                    }
                    else
                    {
                        arr = arrd.ObterArr(Convert.ToInt32(pars[1].Substring(0, 2)));
                    }

                    if (arr.Arredonda_recebe < 1)
                    {
                        valorArr = Convert.ToDecimal(pars[0]) + Convert.ToDecimal(arr.Arredonda_recebe);
                        venda = Convert.ToDouble(valorArr);
                    }
                    else
                    {
                        valorArr = Convert.ToDecimal(pars[0]) + Convert.ToDecimal(arr.Arredonda_recebe);
                        venda = Convert.ToDouble(valorArr);
                    }
                }

                double addDesconto = venda - (venda * Convert.ToDouble(qt.desconto) / 100);

                qt.S_merc_tarif_vendaNet = Convert.ToDecimal(addDesconto);
                qt.Transf_vendaNet = Convert.ToDecimal(addDesconto);
                qt.Transf_venda = Convert.ToDecimal(addDesconto);
                qt.Transf_total = Convert.ToDecimal(addDesconto);
                qt.Transf_valor = Convert.ToDecimal(vall);

                qtdal.AtualizarValores(qt);

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        #endregion

        protected void MostrarMsg(string Msg)
        {
            ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "call me", "showAutoCloseMessage('" + Msg + "')", true);
        }

    }
}